/**
 * @author jeroham
 * Sale Class
 */
/*
 Tasks:
 
 OK Create import scheme, xml/csv->sqlite, :-)
 OK Import of Excel!!!
 OK Update Abonos to Payments
 OK create drop of abonos 
 OK Make sure transactions are by Year!!, delete others or filter
 - user/system options
 OK verify sales history on pocket
 * change button size & color
 OK Search customer is wrong
 OK History customer is not ordered
 OK City load last list form existing
 OK Sale: cambiar costo
 OK Eliminate import buttons
 OK product type not loading
 OK sale to receipt
 OK Payment pass on a single click
 OK Change imported paytypes to english, or all to spanish
 OK Numeric Padd+++++
 OK Fix Sales, (num pad?)
 * Add hour column??
 OK sale history not in order desc
 OK reports, year initialy does not returns anything
 OK fix dates on sales and payment to accepted format yyyy-mm-dd
 OK fix buttons on payment
 OK load on history (customer)
 OK Paypad on Payment
 * Quick pay on payment
 - MANUAL  USER
 
 
 OK Payments on sale, arrange
 OK product types arrange
 OK delete tables on pocket / layout reset option OK
 OK remove query output on report or sale history
 OK save on sales not workin on pocket.
 OK remove alerts on sale after making sure it saves well
 
 *. create alternate theme
 *. Favorite customers --future add on
 *. index, add day statistics
 *. POs and receive PO/inventory
 *. year to year statistics, ex: dec 2009-feb 2010
 
 OK. sales, receipt/view sale
 OK. sales,  history
 OK. Verify query limits up to 10-20 possibly
 NO DeleteItem() = delete from temp and db
 OK customer history
 OK. Add Reports. Ask Year, display today, month, ytd: credit, costs, profi	ts, sales
 OK Add tabs to customer page= sales, payments: list and add payment.
 OK. Change on sale and payment on account
 
 */
var db;
var itembox = new SaleItemBox();
var itemSearchResult = '';
var dbSaleName = '';
var dbSaleItemName = '';
var dbSalePaymentName = '';
var CustomerPaymentDBName = '';
var searchBookmark = 0;
/*
 * TODO:
 * Check status
 * no save on cero valued payments
 * customer payment
 * change item qty and update
 * reports: sales, costs, profits, by range, credit balancing
 * customer payment history
 * import schema
 */

//var query = location.search;
//var id = query.substring(query.indexOf("id=") + 3,query.indexOf("&year")); //query.length);
                  
init();
//Check if there's an active sale and load it, or create a new one
//LoadSale();

document.all.saledate.value = StandardDate(currentDate);//+ ' ' + currentDate.toLocaleTimeString();
ChangeTab(0);
LoadItems();
Load(0); //load default customer , cash

  			
            function ChangeCustomer(option){  //no longer used
                if (option == 0) 
                    document.all.customersearch.style.display = 'none';
                else 
                    document.all.customersearch.style.display = 'inline';
            }
            
            function ChangeTab(item){
				
				
                /*
                 if (item == 0)
                 document.all.infobutton.style.opacity = 1;
                 else
                 document.all.infobutton.style.opacity = .5;
                 if (item == 1)
                 document.all.itemsbutton.style.opacity = 1;
                 else
                 document.all.itemsbutton.style.opacity = .5;
                 if (item == 2)
                 document.all.searchbutton.style.opacity = 1;
                 else
                 document.all.searchbutton.style.opacity = .5;
                 */
				 if (item == 8) //date pad 8, reserved 
                    document.all.datepad.style.display = 'inline';
                else 
                    document.all.datepad.style.display = 'none';
				  if (item == 7) //num pad 7, reserved 
                    document.all.numpad.style.display = 'inline';
                else 
                    document.all.numpad.style.display = 'none';
				 if (item == 4) 
                    document.all.customersearch.style.display = 'inline';
                else 
                    document.all.customersearch.style.display = 'none';
                if (item == 3) //item details
                    document.all.iteminfo.style.display = 'inline';
                else 
                    document.all.iteminfo.style.display = 'none';
                if (item == 2) {
					document.all.paytab.style.display = 'inline';
					ChangePay(null,0,null);
				}
				else 
					document.all.paytab.style.display = 'none';
                if (item == 1) 
                    document.all.itemstab.style.display = 'inline';
                else 
                    document.all.itemstab.style.display = 'none';
                if (item == 0) 
                    document.all.infotab.style.display = 'inline'
                else 
                    document.all.infotab.style.display = 'none';
            }

function LoadItems(){

    //itemid, qty, price,cost,desc, taxA, taxB)
    
    var items = document.all.itemspan;
    var html = "<table border='1'>";
    html += "<th class='itemth' width='15' >Qty</th><th class='itemth' width='80'>Item</th><th class='itemth'  width='45' >Price</th><th class='itemth'  width='45' >SubTotal</th>";
    //alert('here');
    var j = 0;
    for (j = 0; j < itembox.Items.length; j++) {
		var itemdescription = '<a href="#" style="color:black;" onclick="LoadItemDetails('+ j +')" >';
		if (itembox.Items[j].QtyOnHand <= 0)
			itemdescription += '<img src="images/warning.ico" width="15%" height="15%">';  
		 itemdescription += itembox.Items[j].Description+'</a>';
        
        if (j % 2 == 0) {
            html += "<tr><td class='itemtd' ><input type='text' style='width:15px;font-size:8px' id='qty" + j + "' value='" + itembox.Items[j].Qty + "' onchange='ChangeItemQty(" + j + ",this.value);' /></td><td class='itemtd' >" + itemdescription + "</td><td class='itemtd' ><input type='text' style='width:45px;font-size:8px' id='price" + j + "' value='" + formatNumber(itembox.Items[j].Price, false) + "' onchange='ChangeItemPrice(" + j + ",this.value);' /></td><td class='itemtd' >" + formatNumber(itembox.Items[j].SubTotal(), true) + "</td></tr>";
        }
        else 
            html += "<tr><td class='itemtdpar' ><input type='text' style='width:15px;font-size:8px' id='qty" + j + "' value='" + itembox.Items[j].Qty + "' onchange='ChangeItemQty(" + j + ",this.value);' /></td><td class='itemtdpar' >" + itemdescription + "</td><td class='itemtdpar' ><input type='text' style='width:45px;font-size:8px' id='price" + j + "' value='" + formatNumber(itembox.Items[j].Price, false) + "' onchange='ChangeItemPrice(" + j + ",this.value);' /></td><td class='itemtdpar' >$" + formatNumber(itembox.Items[j].SubTotal(), true) + "</td></tr>";
    }
    
    document.all.itemsbutton.value = 'Items(' + itembox.Items.length + ')';
    //blanks
    for (var i = j + 1; i < 10; i++) {
        if (i == j + 1) //editing line
        {
            if (itemSearchResult != '') 
                html += "<tr><td class='itemtd' ></td><td class='itemtd' >" + itemSearchResult + "</td><td class='itemtd' ><input type='button'  value='Clear' style='width:45px;font-size:8px' onclick='SearchItem(null);'	/></td><td class='itemtd' ></td></tr>";
            else 
                html += "<tr><td class='itemtd' ></td><td class='itemtd' ><span id='editline' name='editline' ><input type='text' style='width:80px;font-size:8px' id='productsearch' /></span></td><td class='itemtd' ><input type='button'  value='Search' style='width:45px;font-size:8px' onclick='SearchItem(document.all.productsearch.value);'	/></td><td class='itemtd' ></td></tr>";
            
        }
        
        //if (i % 2 == 0) 
        //    html += "<tr><td class='itemtd' >&nbsp;</td><td class='itemtd' ></td><td class='itemtd' ></td><td class='itemtd' ></td></tr>";
        //else 
        //    html += "<tr><td class='itemtdpar'>&nbsp;</td><td class='itemtdpar' ></td><td class='itemtdpar' ></td><td class='itemtdpar' ></td></tr>";
    }
    html += "<tr><td class='' ></td><td class='' ></td><td class='' ></td><td class='' ></td></tr>";
    
    html += "<tr><td class='' ></td><td class='' ></td><td class='itemtdtotal' >SUBTOTAL</td><td class='itemtdtotal' >" + currencySymbol + itembox.SubTotal().toFixed(2) + "</td></tr>";
    html += "<tr><td class='' ></td><td class='' ></td><td class='itemtdtotal' >TAX</td><td class='itemtdtotal' >" + currencySymbol + itembox.Taxes().toFixed(2) + "</td></tr>";
    html += "<tr><td class='' ></td><td class='' ></td><td class='itemtdtotal' >TOTAL</td><td class='itemtdtotal' >" + currencySymbol + itembox.Total().toFixed(2) + "</td></tr>";
    html += "</table>";
    items.innerHTML = html;
    
    ChangePay(null, 0, false);
    
    
}

function PrintItems(){

    //itemid, qty, price,cost,desc, taxA, taxB)
    
    var items = document.all.itemspan;
    var html = "<table class='iteminfo'>";
    
    html += "<tr ><td width='30px' style='border-bottom: solid thin;'>Qty</td><td  style='border-bottom: solid thin;'>Item</td><td style='width:60px;text-align:right;border-bottom: solid thin;'>SubTotal</td></tr>";
    
    
    //alert('here');
    var j = 0;
    //<tr><td width='30px' >3</td><td>Pizza mediana c/chorizo</td><td style='width:60px;text-align:right;'>7.99</td></tr>
    for (j = 0; j < itembox.Items.length; j++) {
        if (j % 2 == 0) {
            html += "<tr><td  style='width:30px'>" + itembox.Items[j].Qty + "</td><td>" + itembox.Items[j].Description + "</td><td style='width:60px;text-align:right;' >" + formatNumber(itembox.Items[j].SubTotal(), true) + "</td></tr>";
        }
        else 
            html += "<tr><td  style='width:30px'>" + itembox.Items[j].Qty + "</td><td >" + itembox.Items[j].Description + "</td><td style='width:60px;text-align:right;'>" + formatNumber(itembox.Items[j].SubTotal(), true) + "</td></tr>";
    }
    html += "<tr ><td width='30px' style='border-bottom: solid thin;'>&nbsp</td><td  style='border-bottom: solid thin;'>&nbsp</td><td style='width:60px;text-align:right;border-bottom: solid thin;'>&nbsp</td></tr>";
    html += "</table>";
    
    items.innerHTML = html;
    
    document.all.taxA.innerHTML = currencySymbol + itembox.SubTotal().toFixed(2);
    document.all.taxB.innerHTML = currencySymbol + itembox.Taxes().toFixed(2);
    document.all.total.innerHTML = currencySymbol + itembox.Total().toFixed(2);
    
    //ChangePay(null, 0, false);


}


/*
 * Class SaleItem
 */
function SaleItem(itemid, qty, qtyonhand, price, cost, description, taxA, taxB){
    this.ItemId = itemid;
    this.Description = description;
    this.Qty = new Number(0.00);
    this.Qty = qty;
    this.QtyOnHand = new Number(0.00);
    this.QtyOnHand = qtyonhand;
    this.Price = new Number(0.00);
    this.Price = price;
    this.Cost = new Number(0.00);
    this.Cost = cost;
    this.TaxA = new Number(0.00);
    this.TaxA = taxA;
    this.TaxB = new Number(0.00);
    this.TaxB = taxB;
    
    this.SubTotal = getItemSubTotal;
    this.TaxTotal = getItemTax;
    this.Total = getItemTotal;
}

function getItemSubTotal(){
    var subTotal = new Number(0.00);
    var qty = new Number(this.Qty);
    var price = new Number(this.Price);
    subTotal = (qty * price);
    
    return subTotal;
}

function getItemTax(){
    return (this.TaxA / 100 + this.TaxB / 100) * this.SubTotal();
}

function getItemTotal(){
    return this.SubTotal + this.TaxTotal;
}

// EOC SaleItem

/*
 * Class SaleItemBox
 */
function SaleItemBox(){
    this.Items = Array();
    this.SubTotal = getSaleSubTotal;
    this.Total = getSaleTotal;
    this.Taxes = getSaleTax;
    
}

function getSaleSubTotal(){
    var total = new Number();
    for (var i = 0; i < this.Items.length; i++) {
        total += this.Items[i].SubTotal();
    }
    return total;
}

function getSaleTax(){
    var total = new Number();
    for (var i = 0; i < this.Items.length; i++) {
        total += this.Items[i].TaxTotal();
    }
    return total;
}

function getSaleTotal(){
    var total = new Number();
    for (var i = 0; i < this.Items.length; i++) {
        total += this.Items[i].SubTotal() + this.Items[i].TaxTotal();
    }
    return total;
}

// EOC SaleItem


/*
 * Sale general functions,
 * a class was not used to prevent waste of resources
 */
function ChangePay(target, amount, full){
    if (target != null) 
        target.value = formatNumber(amount, false);
    var cashV = new Number();
    var checkV = new Number();
    var creditV = new Number();
    var accountV = new Number();
    cashV = document.all.cash.value;
    checkV = document.all.check.value;
    creditV = document.all.credit.value;
    accountV = document.all.account.value;
    //document.all.cash.value = 0;
    document.all.balance.value = formatNumber(itembox.Total() - cashV - checkV - creditV - accountV, true);
    if (target != null & full) {
        target.value = formatNumber(itembox.Total() - cashV - checkV - creditV - accountV, false);
        document.all.balance.value = formatNumber(0, true);
    }
}

function LoadSale(id){
	
	if (!google.gears.factory || !db) {
        return;
    }
	//var edit = document.all.editline;
    var query = 'select s.id,saledate,status,memo, firstname, middlename, lastname from ' + dbSaleName;
    query += ' s inner join Customer c on c.id=customerid '
    query += ' where s.id =' + id;
    //document.all.memo.innerHTML = query;
    var rs = db.execute(query);
	//alert(query);
    if (rs.isValidRow()) {
        var saleid = document.all.saleid;
        var customer = document.all.customer;
        var saledate = document.all.saledate;
        var memo = document.all.memo;
        
        saleid.innerHTML = '#' + rs.field(0);
        customer.innerHTML = 'Customer: ' + getFullName(rs.field(4), rs.field(5), rs.field(6));
        saledate.innerHTML = 'Date: ' + rs.field(1);
        if (rs.field(3) != '') {
            //if (confirm('memo:' + rs.field(3) + '. Print memo?') == true) 
                memo.innerHTML = 'memo: ' + rs.field(3);
        }
        rs.close();
        
    }
	//alert(customer.innerHTML);
	
    LoadItemsFromTemp(id);
	
    PrintItems();
    
    //print payments
    var query = 'select paytype,amount from ' + dbSalePaymentName;
    query += ' inner join ' + dbSaleName + ' s on s.id=saleid '
    query += ' where s.id =' + id;
    var html = "<table class='iteminfo'>";
    var rs = db.execute(query);
    while (rs.isValidRow()) {
        html += "<tr><td style='width:145px;text-align:right;'>" + rs.field(0) + "</td> <td  style='text-align:right'>" + formatNumber(rs.field(1), true) + "</td></tr>";
		rs.next();
    }
    rs.close();
    html += "</table>"
    document.all.tendered.innerHTML = html;
    
}

function FinishSale(option){
    if (option == '2') {
        //if (confirm('Delete current sale?') == true) {
            Reset();
            return;
    }
    
	var customerid = document.all.customerid.value;
    
    if (itembox.Items.length == 0) {
        if (option != '2') 
            alert('Nothing to sell');
        return;
    }
    
    var balance = new String();
    balance = document.all.balance.value;
    var balanceN = new Number();
    balanceN = balance.replace('$', '').valueOf();
    //alert(balanceN);
    if (balanceN > 0) {
        alert('Balance: ' + balance + ', please enter payment(s)');
        return;
    }
    
	
    var account = document.all.account.value;
    if (customerid == 1 & account > 0) {
        alert('Cash sale cannot have a account payment');
        return;
    }
	
    Save(option);
    SaveItemBox();
	

    if (account > 0) 
        SavePayment('Account', account);
	
    var cash = document.all.cash.value;
    if (cash > 0) 
        SavePayment('Cash', cash);
	
    var check = document.all.check.value;
    if (check > 0) 
        SavePayment('Check', check);
	
    var credit = document.all.credit.value;
    if (credit > 0) 
        SavePayment('Credit', credit);
		
		
	alert('Sale finished. Change: ' + formatNumber(-balanceN, true));
	
    if (customerid != 1 & -balanceN > 0) 
		if(confirm('Change: ' + formatNumber(-balanceN, true)+', Credit this amount to customer?') == true)
			SaveCustomerPayment(customerid, document.all.saledate.value, 'Cash', -balanceN);
	location.replace('saleview.html?id=' + document.all.saleid.value+ '&year='+ currentDate.getFullYear() );
    
}

function Reset(){
    location.replace('index.html');
}

// Open this page's local database.
function init(reset){
    var success = false;
    
    if (window.google && google.gears) {
        try {
            db = google.gears.factory.create('beta.database');
            
            if (db) {
                db.open('psdb');
                
				
                dbSaleName = "Sale_" + currentDate.getFullYear();
                dbSaleItemName = "SaleItem_" + currentDate.getFullYear();
                dbSalePaymentName = "SalePayment_" + currentDate.getFullYear();
				CustomerPaymentDBName = "CustomerPayment_" + currentDate.getFullYear();
                
                if (reset=="reset") {
					if (confirm('Reset DB?') == true) {
						db.execute('drop table ' + dbSaleName);
						db.execute('drop table ' + dbSalePaymentName);
						db.execute('drop table ' + dbSaleItemName);
						alert('Done');
					}
                }
				//fixes abonos-> payments
				  if (reset=="fix") {
					if (confirm('Reset DB?') == true) {
						db.execute('select s.id, saledate,amount,paytype from sale_2009 s inner join saleitem_2009 is on s.id=saleid  where itemid=1');
						//db.execute('drop table ' + dbSalePaymentName);
						//db.execute('drop table ' + dbSaleItemName);
						alert('Done');
					}
                }
                db.execute('create table if not exists ' + dbSaleName +
                ' (id int primarykey,' +
                ' saledate datetime,' +
                ' customerid text,' +
                ' status int,' + //status; 0 current, 1 open, 2 closed, 3 void
                ' memo text' +
                ')');
                
                db.execute('create table if not exists ' + dbSalePaymentName +
                ' (id int primarykey,' +
                ' saleid int,' +
                ' paytype text,' +
                ' amount real' +
                ')');
                
                db.execute('create table if not exists ' + dbSaleItemName +
                ' (id int primarykey,' +
                ' saleid int,' +
                ' itemid int,' +
                ' description text,' +
                ' qty real,' +
                ' cost real,' +
                ' price real,' +
                ' taxes real' +
                ')');
                
				//create indexes
				db.execute('create index if not exists ' + dbSaleName + 'ix on ' + dbSaleName + ' (id,saledate,customerid);');
				
                success = true;
                // Initialize the UI at startup.
            
                //displayRecentPhrases();
                // loadSaleTypes('');
            }
            
        } 
        catch (ex) {
            setError('Could not create database: ' + ex.message);
            alert('Could not create database: ' + ex.message);
        }
    }
    
    // Enable or disable UI elements
    
    var inputs = document.forms[0].elements;
    for (var i = 0, el; el = inputs[i]; i++) {
        el.disabled = !success;
    }
}

function Save(status){
	if (!google.gears.factory || !db) {
		return;
	}
	
	var saleid = document.all.saleid;
	var customerid = document.all.customerid;
	var saledate = document.all.saledate;
	var memo = document.all.memo;
	// var status = document.all.status;
	
	
	var saleidT = saleid.value;
	var customeridT = customerid.value;
	var saledateT = FormatDate(saledate.value);
	var memoT = memo.value;
	var statusT = status;
	
	
	
	//insert or update
	// if (saleidT == '0') {
	//get the new id
	var rs = db.execute('select max(id)+1 from ' + dbSaleName);
	var newid = 0;
	
	newid = rs.field(0);
	
	if (newid == null) {
		newid = 1;
		statusT = 0;
	}
	rs.close();
	
	// Insert the new item.
	// The Gears database automatically escapes/unescapes inserted values.
	db.execute('Insert into ' + dbSaleName + ' (id, customerid, saledate, memo, status) values (?,?,?,?,?)', [newid, customeridT, saledateT, memoT, statusT]);
	//alert('Sale added.');
	saleid.value = newid;
	//}
	// else {
	//   db.execute('Update ' + dbSaleName + ' Set customerid=?, saledate=?, memo=?, status=? where id=?', 
	//	[customeridT, saledateT, memoT, statusT, SaleidT]);
	// alert('Sale updated.');
//}
    
}

function Delete(id){
    if (id > 0) {
    
        var a = confirm('Delete the Sale?');
        if (a != false) {
        
            db.execute('delete from ' + dbSaleName + ' where id= id='+ id);
            alert('Sale deleted!');//
            //Load first record as default..or display a top 20 search? 
            //var rs = db.execute('select top 1 id from ' + dbSaleName + '');
            
            Search('');
        }
    }
    
}

function LoadItem(id){
    if (id > 0) {
        var query = 'select product.id, price, cost';
        query += ', quantity, taxrate1, taxrate2, brand, description'
        query += ' from product inner join producttype on producttype.id=type where product.id=' + id;
        // alert(query);
        var rs = db.execute(query);
        
		//var itemdescription = '<a href="#" style="color:black;" onclick="LoadItemDetails('+ itembox.Items.length +')" >';
		//if (rs.field(3) <= 0)
		//	itemdescription += '<img src="images/warning.ico" width="15%" height="15%">';  
		// itemdescription += rs.field(7) + '-' + rs.field(6)+'</a>';
        
		 var itemdescription = rs.field(7) + '-' + rs.field(6);
		 
        itembox.Items.length++;
        
        itembox.Items[itembox.Items.length - 1] = new SaleItem(rs.field(0), 1, rs.field(3), rs.field(1), rs.field(2), itemdescription, rs.field(4), rs.field(5));
        //itemid, qty, qtyonhand, price, cost, description, taxA, taxB
        itemSearchResult = ''; //reset search
        //alert(itembox.Items[itembox.Items.length - 1].Description);
        
        LoadItems();
        rs.close();
    }
}

function LoadItemDetails(index){
		document.all.itemdescription.innerHTML = itembox.Items[index].Description;
    	document.all.itemcost.value = formatNumber(itembox.Items[index].Cost,false);
		document.all.itemprice.value = formatNumber(itembox.Items[index].Price,false);
		document.all.itemqty.value = itembox.Items[index].Qty;
		document.all.editingindex.value = index;
		ChangeTab(3);
}

function SaveItemDetails(){
   
   		var index = document.all.editingindex.value;
		var cost = document.all.itemcost.value;
		var price = document.all.itemprice.value ;
		var qty = document.all.itemqty.value;
       	
		price = parseFloat(price);
		qty = parseInt(qty);		
		cost = parseInt(cost);		
		
		itembox.Items[index].Cost = cost;
		itembox.Items[index].Price= price;
		itembox.Items[index].Qty= qty;
		LoadItems();
		ChangeTab(1);
}

function ChangeItemPrice(index, price){
    price = parseFloat(price);
	itembox.Items[index].Price = price;
    LoadItems();
}

function ChangeItemQty(index, qty){
    qty = parseInt(qty);
	if(qty==0)
		itembox.Items.remove(index);
	else
		itembox.Items[index].Qty = qty;
    LoadItems();
}

function DeleteItem(index){
 itembox.Items.remove(index);
 LoadItems();
ChangeTab(1);
}


function LoadItemsFromTemp(id){


    if (id > 0) {
        var query = 'select itemid, si.price, si.cost, si.qty, product.quantity, '
        query += 'taxrate1, taxrate2, brand, si.description';
        query += ' from product inner join producttype on producttype.id=type ';
        query += ' inner join ' + dbSaleItemName + ' si on product.id=itemid where saleid=' + id;
        var rs = db.execute(query);
        
        while (rs.isValidRow()) {
            itembox.Items.length++;
            itembox.Items[itembox.Items.length - 1] = new SaleItem(rs.field(0), rs.field(3), rs.field(4), rs.field(1), rs.field(2), rs.field(7) + '-' + rs.field(8), rs.field(5), rs.field(6));
            rs.next();
        }
        
        rs.close();
    }
}

//Saves all items in the current itembox
function SaveItemBox(){
    for (var i = 0; i < itembox.Items.length; i++) {
        SaveItem(i);
    }
}

function SaveItem(index){
    if (!google.gears.factory || !db) {
        return;
    }
    var saleid = document.all.saleid;
    var saleidT = saleid.value;
	
	
		var newid = 0;
		var rs = db.execute('select max(id)+1 as pid from ' + dbSaleItemName);
		newid = rs.field(0);
		rs.close();
		if (newid == null) 
			newid = 1;
		db.execute('Insert into ' + dbSaleItemName + ' (id,saleid,itemid,description,qty,cost,price,taxes) values (?,?,?,?,?,?,?,?)', [newid, saleidT, itembox.Items[index].ItemId, itembox.Items[index].Description, itembox.Items[index].Qty, itembox.Items[index].Cost, itembox.Items[index].Price, itembox.Items[index].TaxTotal()]);
		//update inventory 
		db.execute('Update Product SET quantity=quantity-? where id=?', [itembox.Items[index].Qty, itembox.Items[index].ItemId]);
	
}
 function SaveCustomerPayment(customerid, paymentdate, paytype, amount){
                if (!google.gears.factory || !db) {
                    alert('Error saving');
                    return;
                }
                var date = FormatDate(paymentdate);
                // The Gears database automatically escapes/unescapes inserted values.
                var rs = db.execute('select max(id)+1 from ' + CustomerPaymentDBName);
                var newid = rs.field(0);
                if (newid == null) 
                    newid = 1;
				rs.close();
                db.execute('insert into ' + CustomerPaymentDBName + ' (id, customerid,paymentdate, paytype, amount)  values (? ,?, ?, ?, ?)', [newid, customerid, date, paytype, amount]);
                //update balance
                db.execute('UPDATE Customer SET balance=balance-? WHERE id=?', [amount, customerid]);
                
                
                
            }

function SearchItem(search){

    itemSearchResult = '';
	
	if (search == null) {
		LoadItems();
		return;
	}
    //var edit = document.all.editline;
    var query = 'select id,brand,description,price,quantity from product where UPC like "%' + search + '%"';
    query += ' OR description like "%' + search + '%"';
    query += ' OR brand like "%' + search + '%"';
    query += ' OR model like "%' + search + '%"';
    query += ' OR [type] like "%' + search+ '%"';
    var html = '<select style="width:80px;" id="itemselect" onchange="LoadItem(this.value)">';
    html += '<option value="0">-Drop To Select-</option>';
    var rs = db.execute(query);
	
    var count = 0;
    while (rs.isValidRow()) {
        if (count >= 20) 
            break;
        
        html += '<option value="' + rs.field(0) + '">' + rs.field(1) + '-' + rs.field(2) + '$' + rs.field(3) + ':Qty:' + rs.field(4) + '</option>';
        count++;
        rs.next();
    }
    html += '</select>';
    
    itemSearchResult = html;
    //edit.innerHtml = html;
    //	alert(itemSearchResult);
    LoadItems();
    rs.close();
}

/* 
 * Customer related functions
 */
function Load(id){
    ChangeTab(0);
    
    var customeridT = document.all.customerid;
    var customerT = document.all.customer;
    
    if (id > 0) {
        var rs = db.execute('select * from Customer where id=' + id);
        
        customeridT.value = id;
       // alert(customeridT.value);
        customerT.value = rs.field(1) + ' ' + rs.field(2) + ' ' + rs.field(3);
        
        rs.close();
    }
    else {
        customeridT.value = 1;
        customerT.value = 'Cash';
        
    }
    //save sale to persist customer change
    //Save();
}

function SearchCustomer(search,option){
	
					searchBookmark = searchBookmark + option;
					if (searchBookmark < 0) 
						searchBookmark = 0;
					var s = new String(search);	
   					var query = 'select * from Customer where ';
					
					if (s.indexOf(' ') > 0) {
						s = s.split(' ');
						
						query += ' (firstname like "%' + s[0] + '%"';
						query += ' AND lastname like "%' + s[1] + '%") OR';
					}
					//else {
						query += ' firstname like "%' + search + '%"';
						query += ' OR lastname like "%' + search + '%"';
				//	}
					query += ' OR middlename like "%' + search + '%"';
					query += ' OR phone like "%' + search + '%"';
					query += ' OR email like "%' + search + '%"';
					query += ' OR city like "' + search + '%"';
					query += ' OR zipcode like "' + search + '%"';
					query += ' OR address1 like "%' + search + '%"';
					query += ' OR address2 like "%' + search + '%"';
					query += ' ORDER BY firstname, lastname asc limit 10 offset ' + searchBookmark;
					
    var status = document.all.searchresult;
	//status.innerHTML = query;
	
    var html = '<div class="field" >Search Results:</div>';//'Searching...' ;
    var rs = db.execute(query);
    var count = 0;
    while (rs.isValidRow()) {
        html += SearchResult4(rs.field(0), getFullName(rs.field(1),rs.field(2),rs.field(3)), 'Tel:' + rs.field(4), 'Bal: ' + formatNumber(rs.field(12), true));
        count++;
        rs.next();
    }
	 if (searchBookmark >= 10) 
                    html += "<a href=# onclick='SearchCustomer(\"" + search + "\",-10);'>[Back]</a>";
                if (count >= 10) 
                    html += "<a href=# onclick='SearchCustomer(\"" + search + "\",10);'>[Next]</a>";
    
	status.innerHTML = html;
	rs.close();
}

/*
 * Payments
 */
function SavePayment(paytype, amount){
    if (!google.gears.factory || !db) {
        return;
    }
    var saleid = document.all.saleid;
    var saleidT = saleid.value;
    var newid = 0;
	var rs = db.execute('select max(id)+1 as pid from ' + dbSalePaymentName);
	
    newid = rs.field(0);
    
    if (newid == null) 
        newid = 1;
    db.execute('Insert into ' + dbSalePaymentName + ' (id,saleid,paytype,amount) values (?,?,?,?)', [newid, saleidT, paytype, amount]);
    if (paytype == 'Account') {
        //update balance
		
        var customerid = document.all.customerid.value;
        db.execute('UPDATE Customer SET balance=balance+? WHERE id=?', [amount, customerid]);
    }
    
}


